import { ArgumentMetadata, HttpException, HttpStatus, Injectable, PipeTransform, ValidationPipe, ValidationPipeOptions } from '@nestjs/common';

@Injectable()
export class DtoPipe implements PipeTransform<any> {
  private options:ValidationPipeOptions = {}
  constructor(options?: ValidationPipeOptions) {
    if(options) {
      this.options = options
    }
  }

  async transform(value: any, metadata: ArgumentMetadata) {
    let v = new ValidationPipe({
        stopAtFirstError : true,
        skipMissingProperties : false,
        whitelist : true,
        transform : true,
        transformOptions : {
        },
        exceptionFactory : (errors) => {
            const constraints = errors[0].constraints
            const keys = Object.keys(constraints)
            throw new HttpException(constraints[keys[0]], HttpStatus.FORBIDDEN);
        },

        ...this.options
    })

    return v.transform(value, metadata)
    
  }
}
